package com.example.bbs.ui.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.bbs.R;
import com.example.bbs.base.Data;
import com.example.bbs.bean.Notice;
import com.example.bbs.bean.Post;
import com.example.bbs.config.HttpConstant;
import com.example.bbs.util.BaseUtil;
import com.example.bbs.util.HttpUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

import okhttp3.FormBody;

public class NoticeActivity extends AppCompatActivity {

    public class ItemViewHolder extends RecyclerView.ViewHolder {

        Notice notice;
        public static final String INTENT_EXTRA_NOTICE = "notice"; // type: Notice

        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);
            itemView.setOnClickListener((v) -> {
//                Intent intent = new Intent(NoticeActivity.this, EditActivity.class);
//                intent.putExtra(DisplayActivity.INTENT_EXTRA_POST, post);
//                startActivity(intent);
                FormBody formBody = new FormBody.Builder()
                        .add(HttpConstant.FIELD_NOTICE_ID, "" + notice.getId())
                        .build();
                HttpUtil.postAsync(HttpConstant.REQUEST_READ_NOTICE, formBody, (response) -> {
                    if (response != null  && response.getBoolean(HttpConstant.FIELD_REPLY)) {
                        Log.i(LOG_TAG, "read notice success");
                    }
                    else {
                        Log.w(LOG_TAG, "read notice failure");
                    }
                });
            });
        }

        public void setNotice(Notice notice) {
            this.notice = notice;
            TextView titleTextView = itemView.findViewById(R.id.tv_item_title);
            if(!notice.isReadOr()){
                titleTextView.setTextColor(getColor(R.color.red));
            }
            else {
                titleTextView.setTextColor(getColor(R.color.black));
            }
            titleTextView.setText("Notice");
            TextView contentTextView = itemView.findViewById(R.id.tv_item_content);
            contentTextView.setText(notice.getContent());
        }
    }

    public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        @NonNull
        @Override
        public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = View.inflate(parent.getContext(), R.layout.view_item_draft_box, null);
            return new ItemViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            ((ItemViewHolder)holder).setNotice(mNoticeList.get(position));
        }

        @Override
        public int getItemCount() {
            return mNoticeList.size();
        }
    }

    static final String LOG_TAG = DraftBoxActivity.class.getSimpleName();
    static final int MIN_REFRESHING_TIME = 1000; // milliseconds

    SwipeRefreshLayout srlNoticeList;
    RecyclerView rvDraftList;
    MyAdapter mAdapter = new MyAdapter();
    List<Notice> mNoticeList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(LOG_TAG, "onCreate");
        setContentView(R.layout.activity_notice);
        initView();
    }

    @SuppressLint("NotifyDataSetChanged")
    private void initView() {
        srlNoticeList = findViewById(R.id.srl_notice_list);
        srlNoticeList.setColorSchemeColors(getResources().getColor(R.color.primary, null));
        rvDraftList = findViewById(R.id.rv_notice_list);
        rvDraftList.setAdapter(mAdapter);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        rvDraftList.setLayoutManager(layoutManager);

        srlNoticeList.setOnRefreshListener(() -> {
            long startTime = System.currentTimeMillis();
            CompletableFuture.runAsync(() -> {
                load();
                long waitingTime = startTime + MIN_REFRESHING_TIME - System.currentTimeMillis();
                if (waitingTime > 0) {
                    srlNoticeList.postDelayed(() -> {
                        if (srlNoticeList != null && srlNoticeList.isRefreshing()) {
                            srlNoticeList.setRefreshing(false);
                        }
                        mAdapter.notifyDataSetChanged();
                    }, waitingTime); // 延时一段时间，关闭下拉刷新
                } else {
                    runOnUiThread(() -> {
                        if (srlNoticeList != null && srlNoticeList.isRefreshing()) {
                            srlNoticeList.setRefreshing(false);
                        }
                        mAdapter.notifyDataSetChanged();
                    });
                }
            });
        });
    }

    private void load() {
        if (Data.myself == null) {
            BaseUtil.showToast(R.string.toast_please_login);
            return;
        }

        JSONObject json = HttpUtil.post(HttpConstant.REQUEST_GET_NOTICE,"");
        if (json == null || !json.getBoolean(HttpConstant.FIELD_REPLY))
            return;
        JSONArray result = json.getJSONArray(HttpConstant.FIELD_DATA);
        mNoticeList.clear();
        for (int i = 0; i < result.size(); i++) {
            Notice notice = result.getObject(i, Notice.class);
            mNoticeList.add(notice);
            Log.d(LOG_TAG, "Notice updated: num: " + mNoticeList.size());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(LOG_TAG, "onResume");

        try {
            CompletableFuture.runAsync(this::load).get(); // 初始化
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(LOG_TAG, "onPause");
    }
}